package com.xez.data
{
	import com.xez.util.FsConst;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;

	public class CacheData
	{
		public function CacheData()
		{
		}
		
		[Bindable]
		public var msg:String;
		
		public function get cachename():String
		{
			return null;
		}
		
		public function get isnew():Boolean
		{
			if (hasCache())
				return false;
			else
				return true;
		}
		
		protected function saveCache(bytedata:ByteArray):void
		{
			trace('缓存数据:', cachename);
			try
			{
				var cachebyte:ByteArray = new ByteArray();
				cachebyte.writeByte(0);
				cachebyte.writeBytes(bytedata, 0, bytedata.bytesAvailable);
				cachebyte.writeByte(0);
				cachebyte.position = 0;
				
				var cacheFile:File = new File().resolvePath(FsConst.cachedataFile.nativePath + '/' + cachename + '.fs');
				trace(cacheFile.nativePath);
				var fs:FileStream = new FileStream();
				fs.open(cacheFile, FileMode.WRITE);
				fs.writeBytes(cachebyte, 0, cachebyte.bytesAvailable);
				fs.close();
				trace('缓存数据成功');
			} 
			catch(error:Error)
			{
				trace('缓存数据失败:', error.message);
			}
		}
		
		protected function hasCache():Boolean
		{
			var cacheFile:File = new File().resolvePath(FsConst.cachedataFile.nativePath + '/' + cachename + '.fs');
			if (cacheFile.exists)
				return true;
			else
				return false;
		}
		
		protected function getCache():ByteArray
		{
			trace('读取缓存数据:', cachename);
			var bytedata:ByteArray;
			
			try
			{
				var cacheFile:File = new File().resolvePath(FsConst.cachedataFile.nativePath + '/' + cachename + '.fs');
				if (cacheFile.exists)
				{
					var cachebyte:ByteArray = new ByteArray();
					bytedata = new ByteArray();
					var fs:FileStream = new FileStream();
					fs.open(cacheFile, FileMode.READ);
					fs.readBytes(cachebyte);
					fs.close();
					
					cachebyte.readByte();
					cachebyte.readBytes(bytedata, 0, cachebyte.bytesAvailable - 1);
					trace('读取缓存数据成功');
				}
			} 
			catch(error:Error)
			{
				trace('读取缓存数据失败:', error.message);
			}
			
			return bytedata;
		}
	}
}